package com.zyasdk.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;

@SuppressLint("SimpleDateFormat")
@SuppressWarnings("deprecation")
public class Util {

	/**
	 * ����ļ����ȡͼƬ
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static int GetImageResIDInResouces(Context context, String fileName) {
		int resID = 0;
		ApplicationInfo appInfo = context.getApplicationInfo();
		try {
			resID = context.getResources().getIdentifier(fileName, "drawable",
					appInfo.packageName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resID;
	}

	/**
	 * ����ɫ#52545f ת��16����
	 * 
	 * @param color
	 * @return
	 */
	public static int ConvertColorToInt(String color) {
		String StrColor = color.replace("#", "");
		int result = 0;
		int length = StrColor.length();
		if (length == 6) {
			result = Color.rgb(Integer.valueOf(StrColor.substring(0, 2), 16),
					Integer.valueOf(StrColor.substring(2, 4), 16),
					Integer.valueOf(StrColor.substring(4, 6), 16));
		} else if (length == 8) {
			result = Color.argb(Integer.valueOf(StrColor.substring(0, 2), 16),
					Integer.valueOf(StrColor.substring(2, 4), 16),
					Integer.valueOf(StrColor.substring(4, 6), 16),
					Integer.valueOf(StrColor.substring(6, 8), 16));
		}
		return result;
	}

	public static String[] getRowCountAndListStr(String str) {
		String[] result = new String[2];
		int index = str.indexOf(",");
		result[0] = Integer.valueOf(str.substring(0, index)) + "";
		result[1] = str.substring(index + 1);
		return result;
	}

	public static Bitmap createBitmapThumbnail(Bitmap bitmap, Context context) {
		Bitmap desBitmap = Bitmap.createBitmap(340, 205, Config.ARGB_8888);
		Canvas canvas = new Canvas();
		canvas.setBitmap(desBitmap);
		Paint paint = new Paint();
		paint.setColor(0xff000000);
		paint.setStyle(Style.FILL);
		canvas.drawRect(0, 0, 437, 210, paint);
		canvas.drawBitmap(bitmap, 0, 0, paint);
		return desBitmap;
	}

	/**
	 * ���ԭͼ�ͱ䳤����Բ��ͼƬ
	 * 
	 * @param source
	 * @param min
	 * @return
	 */
	public Bitmap createCircleImage(Bitmap source, int min) {
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888);
		/**
		 * ����һ��ͬ���С�Ļ���
		 */
		Canvas canvas = new Canvas(target);
		/**
		 * ���Ȼ���Բ��
		 */
		canvas.drawCircle(min / 2, min / 2, min / 2, paint);
		/**
		 * ʹ��SRC_IN
		 */
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		/**
		 * ����ͼƬ
		 */
		canvas.drawBitmap(source, 0, 0, paint);
		return target;
	}

	/**
	 * ��assets�е������ļ����Ƶ�sdcard��(path="/sdcard/.../")
	 * 
	 * @param context
	 */
	public static void copyFileToSdcard(Context context, String fileName,
			String dstPath) {

		try {
			File dir = new File(dstPath);
			if (!dir.exists())
				dir.mkdir();
			AssetManager assetManager = context.getAssets();
			byte[] buffer = new byte[1024];
			int readLen = 0;
			// �����ļ�
			File dstFile = new File(dstPath + fileName);
			FileOutputStream out = new FileOutputStream(dstFile);
			InputStream in = assetManager.open(fileName);
			while ((readLen = in.read(buffer)) != -1) {
				out.write(buffer, 0, readLen);
			}
			out.flush();
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * �õ���ǰʱ���ַ� 2010-10-10 00:00:00
	 * 
	 * @author HeCheng
	 * @time 2011-01-08 16:10:16
	 */
	public static String CurrentTimeStr(boolean isLong) {
		Date a = new Date();
		String result = a.getYear()
				+ 1900
				+ "-"
				+ (a.getMonth() + 1 < 10 ? "0" + (a.getMonth() + 1) : a
						.getMonth() + 1) + "-"
				+ (a.getDate() < 10 ? "0" + a.getDate() : a.getDate());
		// �����Ҫ�ܳ���
		if (isLong)
			result += " "
					+ (a.getHours() < 10 ? "0" + a.getHours() : a.getHours())
					+ ":"
					+ (a.getMinutes() < 10 ? "0" + a.getMinutes() : a
							.getMinutes())
					+ ":"
					+ (a.getSeconds() < 10 ? "0" + a.getSeconds() : a
							.getSeconds());
		return result;
	}

	/**
	 * ����ʱ�����
	 * 
	 * @param data
	 */
	public static String computeData(String data) {
		String result = "";
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date time1 = new Date();
			Date time2 = df.parse(data);
			long l = Math.abs(time1.getTime() - time2.getTime());
			long day = l / (24 * 60 * 60 * 1000);
			long hour = (l / (60 * 60 * 1000) - day * 24);
			long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
			if (day > 0) {
				return day + " ��";
			} else if (hour > 0) {
				return hour + " Сʱ";
			} else if (min > 0) {
				return min + " ����";
			} else {
				return "1 ����";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String returnPercent(double fen) {
		String baifenbi = "";// ���ܰٷֱȵ�ֵ
		// NumberFormat nf = NumberFormat.getPercentInstance(); ע�͵���Ҳ��һ�ַ���
		// nf.setMinimumFractionDigits( 2 ); ������С����λ
		DecimalFormat df1 = new DecimalFormat("##.00%"); // ##.00%
		// �ٷֱȸ�ʽ�����治��2λ����0����
		// baifenbi=nf.format(fen);
		baifenbi = df1.format(fen);
		if (baifenbi.indexOf(".") == 0)
			baifenbi = "0" + baifenbi;
		return baifenbi;
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static float dip2px2Float(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return dpValue * scale + 0.5f;
	}

	/**
	 * ��pxֵת��Ϊdip��dpֵ����֤�ߴ��С����
	 * 
	 * @param pxValue
	 * @param scale
	 *            ��DisplayMetrics��������density��
	 * @return
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static String getStringInWeek(Date date) {
		String w = "";
		int we = date.getDay();
		switch (we) {
		case 1:
			w = "����һ";
			break;
		case 2:
			w = "���ڶ�";
			break;
		case 3:
			w = "������";
			break;
		case 4:
			w = "������";
			break;
		case 5:
			w = "������";
			break;
		case 6:
			w = "������";
			break;
		case 0:
			w = "������";
			break;
		}
		return w;
	}

	public static String getMinuter(Date date) {
		String m = "";
		int mi = date.getMinutes();
		m = mi < 10 ? "0" + mi : mi + "";
		return m;
	}

	public static String getHour(Date date) {
		String h = "";
		int ho = date.getHours();
		h = ho < 10 ? "0" + ho : ho + "";
		return h;
	}

	public static String getDate(Date date) {
		String d = "";
		int da = date.getDate();
		d = da < 10 ? "0" + da : da + "";
		return d;
	}

	public static String getMonth(Date date) {
		String m = "";
		int month = date.getMonth() + 1;
		m = month < 10 ? "0" + month : month + "";
		return m;
	}

	public static String getYear(Date date) {
		String yaer = (date.getYear() + 1900) + "";
		return yaer;
	}

	public static String getTime() {
		Date date = new Date();
		String time = "";
		time = getYear(date) + "-" + getMonth(date) + "-" + getDate(date);
		return time;
	}

	/**
	 * yyyy-MM-dd hh:mm:ss תΪ���ڶ���
	 * 
	 * @param date
	 * @return
	 */
	public static Date ConvertStringToDate(String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
			return sdf.parse(date);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * dateתyyyy-MM-dd hh:mm:ss
	 * 
	 * @param date
	 * @return
	 */
	public static String convertDateToString(Date a) {
		String result = a.getYear()
				+ 1900
				+ "-"
				+ (a.getMonth() + 1 < 10 ? "0" + (a.getMonth() + 1) : a
						.getMonth() + 1) + "-"
				+ (a.getDate() < 10 ? "0" + a.getDate() : a.getDate()) + " "
				+ (a.getHours() < 10 ? "0" + a.getHours() : a.getHours()) + ":"
				+ (a.getMinutes() < 10 ? "0" + a.getMinutes() : a.getMinutes())
				+ ":"
				+ (a.getSeconds() < 10 ? "0" + a.getSeconds() : a.getSeconds());
		return result;
	}

	/**
	 * ��ͼƬ��ȡΪԲ��ͼƬ
	 * 
	 * @param bitmap
	 *            ԭͼƬ
	 * @param ratio
	 *            ��ȡ���������8����Բ�ǰ뾶�ǿ�ߵ�1/8�������2������Բ��ͼƬ
	 * @return Բ�Ǿ���ͼƬ
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float ratio) {

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio,
				bitmap.getHeight() / ratio, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * ��ȡԲ��λͼ�ķ���
	 * 
	 * @param bitmap
	 *            ��Ҫת����Բ�ǵ�λͼ
	 * @param pixels
	 *            Բ�ǵĶ�����ֵԽ��Բ��Խ��
	 * @return ������Բ��λͼ
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * ��ȡ��Ϣ���͵��û���Ϣ
	 * 
	 * @param context
	 * @return
	 */
	public static String getPushUserInfo(Context context) {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(context);
		String userID = sp.getString("push_user_info", "");
		return userID;
	}

	/**
	 * ������Ϣ���͵��û���Ϣ
	 * 
	 * @param context
	 * @param info
	 */
	public static void setPushUserInfo(Context context, String info) {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor editor = sp.edit();
		editor.putString("push_user_info", info);
		editor.commit();
	}

	/**
	 * ��ȡ�����ļ����
	 * 
	 * @param context
	 * @param metaKey
	 * @return
	 */
	public static String getMetaValue(Context context, String metaKey) {
		Bundle metaData = null;
		String value = null;
		if (context == null || metaKey == null) {
			return null;
		}
		try {
			ApplicationInfo ai = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);
			if (null != ai) {
				metaData = ai.metaData;
			}
			if (null != metaData) {
				value = metaData.getString(metaKey);
			}
		} catch (NameNotFoundException e) {

		}
		return value;
	}

	public static String getIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	public static String getCurrentTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());// ��ȡ��ǰʱ��
		String str = formatter.format(curDate);
		return str;
	}

	public static final int NETWORK_TYPE_NONE = -0x1; // �������
	public static final int NETWORK_TYPE_WIFI = 0x1; // WiFiģʽ
	public static final int NETWOKR_TYPE_MOBILE = 0x2; // gprsģʽ

	/**
	 * ��ȡ��ǰ����״̬������
	 * 
	 * @param mContext
	 * @return
	 */
	public static int getCurrentNetType(Context mContext) {
		ConnectivityManager connManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifi = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // wifi
		NetworkInfo gprs = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); // gprs

		if (wifi != null && wifi.getState() == State.CONNECTED) {
			return NETWORK_TYPE_WIFI;
		} else if (gprs != null && gprs.getState() == State.CONNECTED) {
			return NETWOKR_TYPE_MOBILE;
		}
		return NETWORK_TYPE_NONE;
	}

	/**
	 * �Ƿ��ǽ���
	 * 
	 * @param date
	 * @return
	 */
	public static boolean isToday(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date(Long.parseLong(date))).equals(
				sdf.format(new Date()));

	}

	/**
	 * �Ƿ�������
	 * 
	 * @param date
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static boolean isYesterday(String date) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String yestoday = sdf.format(calendar.getTime());
		return yestoday.equals(sdf.format(new Date(Long.parseLong(date))));
	}

	public static String fromDate(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date(Long.parseLong(date)));
	}

	public static boolean isNull(Object obj) {
		if (obj == null) {
			return true;
		}
		if (obj instanceof String) {

		} else if (obj instanceof Map<?, ?>) {
			Map<?, ?> map = (Map<?, ?>) obj;
			if (map.size() == 0) {
				return true;
			}
		}
		return false;
	}

	public static boolean isHomepage(String str) {
		if (str.indexOf("http") == -1 && str.indexOf("https") == -1
				&& str.indexOf("ftp") == -1) {
			str = "http://" + str;
		}
		Pattern p = Pattern
				.compile(
						"^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-"
								+ "Z0-9\\.&%\\$\\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{"
								+ "2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}"
								+ "[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|"
								+ "[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-"
								+ "4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0"
								+ "-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.[a-zA-Z]{2,4})(\\:[0-9]+)?(/"
								+ "[^/][a-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$\\=~_\\-@]*)*$",
						Pattern.CASE_INSENSITIVE);
		return p.matcher(str).matches();
	}

	/**
	 * 将字符串转换成16进制
	 * 
	 * @param s
	 * @return
	 */
	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	}

	/**
	 * 将16进制转换成字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String toStringHex(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	public static int getStringId(Context context, String name) {
		return getIdentifier(context, name, "string");
	}

	public static int getDrawableId(Context context, String name) {
		return getIdentifier(context, name, "drawable");
	}

	public static int getId(Context context, String name) {
		return getIdentifier(context, name, "id");
	}

	public static int getLayoutId(Context context, String name) {
		return getIdentifier(context, name, "layout");
	}

	public static int getStyleId(Context context, String name) {
		return getIdentifier(context, name, "style");
	}

	public static int getIdentifier(Context context, String name, String type) {
		Resources res = context.getResources();
		return res.getIdentifier(name, type, context.getPackageName());
	}

	/**
	 * 获取Assets下的图片
	 * 
	 * @param fileName
	 * @return
	 */
	public static Bitmap getAssetsBitmap(Context context, String fileName) {
		try {
			InputStream stream = null;
			try {
				stream = context.getResources().getAssets().open(fileName);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return BitmapFactory.decodeStream(stream);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Drawable getAssetsDrawable(Context context, String fileName) {
		try {
			Bitmap bitmap = getAssetsBitmap(context, fileName);
			if (bitmap == null)
				return null;
			//判断图片是否支持.9图片
			byte[] chunk = bitmap.getNinePatchChunk();
			if (chunk == null) {
				//不支持.9图片直接返回
				return new BitmapDrawable(bitmap);
			}
			NinePatchDrawable patchy = new NinePatchDrawable(bitmap, chunk,
					new Rect(), null);
			return patchy;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 判断是否为横屏
	 * 
	 * @return
	 */
	public static boolean isScreenChange(Context context) {
		Configuration mConfiguration = context.getResources()
				.getConfiguration(); // 获取设置的配置信息
		int ori = mConfiguration.orientation; // 获取屏幕方向
		if (ori == Configuration.ORIENTATION_LANDSCAPE) {
			// 横屏
			return true;
		} else if (ori == Configuration.ORIENTATION_PORTRAIT) {
			// 竖屏
			return false;
		}
		return false;
	}
}
